<?php

require_once ('common.php');
if (!$user['is_admin'])
{
    header('location: ' . APP_URL);
    exit;
}
$news_id = trim($_REQUEST['id']);
$action = trim($_REQUEST['action']);
$news = $db->query('SELECT * FROM bbs_news ORDER BY news_id');
if (!empty($news))
{
    foreach ($news as $n)
    {
        $n['news_text'] = $bbcode->coverpass(limit_string($n['news_text'], 40));
        $n['news_time'] = getStrTime($n['news_time']);
        $nr[] = $n;
    }
    $news = $nr;
}
if ($action == 'addnews')
{
    $news_text = trim(stripslashes(htmlspecialchars($_POST['news_text'])));
    $db->insertRow('bbs_news', array('news_text' => $news_text, 'news_time' => getTime(), 'is_show' => 1));
    header('location: ' . APP_URL . '/admin');
    exit;
} 
elseif ($action == 'deletenews')
{
    if (!empty($news_id))
    {
        if ($db->query('DELETE FROM bbs_news WHERE news_id = %1', $news_id))
        {
            die('{"status":"success"}');
        }
    }
} 
elseif ($action == 'togglenewsshow')
{
    checkSession($_POST['session']);
    $is_show = trim($_POST['is_show']);
    if (!empty($news_id) && !empty($is_show))
    {
        $is_show = ($is_show == 'yes') ? 1 : 0;
        $db->updateRow('bbs_news', array('news_id' => $news_id), array('is_show' => $is_show));
        die('{"status":"success"}');
    }
    else
        die('{"status":"error"}');
}
elseif ($action == 'editsettings')
{
	checkSession($_POST['session']);
	foreach ($_POST as $k => $v)
	{
		if (empty($v)) 
		{
			 header('location: ' . APP_URL . '/admin');
			 exit;
		}
		if($k != 'action' && $k != 'session')
		{
			$db->updateRow('bbs_settings', array('key' => $k), array('value' => $v));
		}
	}
    header('location: ' . APP_URL . '/admin');
    exit;	
}
$smarty->assign('pageid', 'admin');
$smarty->assign('pagetitle', 'การจัดการระบบ');
$smarty->display('header.html');
$smarty->assign('news', $news);
$smarty->display('admin.html');
require_once ('sidebar.php');
require_once ('footer.php');

?>